package com.itcast.activiti.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.activiti.entity.ApproveDefinition;
import com.itcast.activiti.entity.ApproveDefinitionHistory;
import com.itcast.activiti.mapper.ApproveDefinitionHistoryMapper;
import com.itcast.activiti.service.IApproveDefinitionHistoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 审批定义表  服务实现类
 * </p>
 *
 * @author itcast
 * @since 2021-03-29
 */
@Service
public class ApproveDefinitionHistoryServiceImpl extends ServiceImpl<ApproveDefinitionHistoryMapper, ApproveDefinitionHistory> implements IApproveDefinitionHistoryService {
    @Override
    public ApproveDefinitionHistory getApproveDefinitionHistory(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public ApproveDefinitionHistory getApproveDefinitionHistory(String deploymentId) {
        return baseMapper.selectOne(new QueryWrapper<ApproveDefinitionHistory>().lambda().eq(ApproveDefinitionHistory::getDeploymentId, deploymentId));
    }

    @Override
    public void insertApproveDefinitionHistory(ApproveDefinition approveDefinition, String deploymentId) {
        ApproveDefinitionHistory approveDefinitionHistory = new ApproveDefinitionHistory();
        BeanUtils.copyProperties(approveDefinition, approveDefinitionHistory);
        approveDefinitionHistory.setId(null);
        approveDefinitionHistory.setApproveDefinitionId(approveDefinition.getId());
        approveDefinitionHistory.setDeploymentId(deploymentId);
        int insert = baseMapper.insert(approveDefinitionHistory);
        if (insert == 0) {
            throw new RuntimeException("create approveDefinitionHistory failure");
        }
    }

    @Override
    public ApproveDefinitionHistory getLastDefinitionByByDefinitionIdAndTenantId(String definitionId, String tenantId) {
        QueryWrapper<ApproveDefinitionHistory> approveDefinitionHistoryQueryWrapper = new QueryWrapper<>();
        approveDefinitionHistoryQueryWrapper.lambda()
                                            .eq(ApproveDefinitionHistory::getApproveDefinitionId, definitionId)
                                            .eq(ApproveDefinitionHistory::getTenantId, tenantId)
                                            .orderByDesc(ApproveDefinitionHistory::getId);
        approveDefinitionHistoryQueryWrapper.last("limit 1");
        return baseMapper.selectOne(approveDefinitionHistoryQueryWrapper);
    }
}
